package com.ruibo.tax.mq.test;

import cn.hutool.core.util.ZipUtil;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQQueue;

import com.ruibo.tax.model.base.PackageHead;
import com.ruibo.tax.model.base.XMLEncodeModel;
import com.ruibo.tax.utils.XMLUtils;
import com.ruibo.tax.utils.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * @author 孙峰
 * @Description: 测试环保对税务发送的数据   这里不采用文件写入的方式   最终失败了
 * @date 2020/12/23 10:58
 */
@Slf4j
@Component
public class ReceiptHB2SWTask {
    //    环保对税务的队列  测试用
    @Resource(name = "QLHB2SW")
    MQQueue hb2swMQQueue;

    @Autowired
    private XMLUtils xmlUtils;

    /**
     * 接受环保对税务的数据测试
     */
    public void receiveZIPMsgFromQLHB2SW() {
        try {
            // 获取对账队列中所有数据
            int currentDepth = hb2swMQQueue.getCurrentDepth();
            if (currentDepth <= 0) {
                log.info("队列中暂无需要处理的数据");
                return;
            }
            for (int i = 0; i < 1; i++) {
                MQMessage retrievedMessage = new MQMessage();
                MQGetMessageOptions getMessageOptions = new MQGetMessageOptions();
                hb2swMQQueue.get(retrievedMessage, getMessageOptions);
                int messageLength = retrievedMessage.getMessageLength();

                log.info("消息的大小为：{}", messageLength);
                byte[] msgData = new byte[messageLength];
                retrievedMessage.readFully(msgData);
                byte[] bytes = ZipUtils.unZip(msgData);
                String s = new String(bytes, Charset.forName("GBK"));
                // 处理接受的数据
                JAXBContext jaxbContext = JAXBContext.newInstance(XMLEncodeModel.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                StringReader stringReader = new StringReader(s);
                XMLEncodeModel xmlEncodeModel = (XMLEncodeModel) jaxbUnmarshaller.unmarshal(stringReader);
                //1、 对接受的数据生成文件保存
                xmlUtils.creteFile(s, xmlEncodeModel);
                //2、保存数据
                // 获取heads。根据heads不同的类型 创建不同的数据解析模型
                PackageHead heads = xmlEncodeModel.getHeads();
                String sjblx = heads.getSJBLX();
                String data = s;
                log.info(data);
                log.info("处理数据成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.toString());
        }
    }


}
